# code:utf8
import json
import logging

import math
from datetime import datetime
from zc_core.model.items import Catalog, Supplier, Sku, ItemData, OrderItem, ItemGroup
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_number, parse_time
from zc_core.util.encrypt_util import short_uuid, build_sha1_order_id, md5
from pyquery import PyQuery
from hsysmall.matcher import *
from zc_core.util.order_deadline_filter import OrderItemFilter
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')
order_filter = OrderItemFilter()


def parse_supplier(response):
    sp_list = list()
    jpy = PyQuery(response.text)
    sp_links = jpy('ul.index_item4_W a')
    for sp in sp_links.items():
        sp_cocde = sp.attr('href').replace("javascript:goList('", '').replace("')", '').replace(";", '').replace('/thirdstoreindex/', 'THIRD_')
        sp_list.append(sp_cocde)

    return sp_list


# 品类解析
def parse_catalog(response):
    jpy = PyQuery(response.text)
    cat1_links = jpy('ul.nav_menu_left a')
    cat23_divs = jpy('div.nav_menu_right div.second_menu')

    cats = list()
    for idx1, cat1_a in enumerate(cat1_links.items()):
        cat1_id = ''
        cat23_div = cat23_divs.eq(idx1)
        cat2_divs = cat23_div.children('div')
        for cat2_div in cat2_divs.items():
            cat2_a = cat2_div('a').eq(0)
            cat2_link = cat2_a.attr('href')
            cat2_id, cat1_id = match_cat_ids(cat2_link)
            cat2_code = match_cat_code(cat2_link)
            cat2_name = cat2_a.text().strip('>').strip()
            cat2 = _build_catalog(cat2_id, cat2_code, cat2_name, cat1_id, 2)
            cats.append(cat2)

            cat3_links = cat2_div('ul.third_menu li a')
            for cat3_a in cat3_links.items():
                cat3_link = cat3_a.attr('href')
                cat3_code = match_cat_code(cat3_link)
                cat3_id, cat1_id = match_cat_ids(cat3_a.attr('href'))
                cat3_name = cat3_a.text().strip()
                cat3 = _build_catalog(cat3_id, cat3_code, cat3_name, cat2_id, 3)
                cats.append(cat3)

        cat1_name = cat1_a.text().strip()
        cat1_code = '{}-{}'.format(cat1_id, cat1_id)
        cat1 = _build_catalog(cat1_id, cat1_code, cat1_name, '', 1)
        cats.append(cat1)

    return cats


def _build_catalog(cat_id, cat_code, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogCode'] = cat_code
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# 处理sku列表总页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    total = jpy('div.total strong')
    if total:
        return math.ceil(int(total.text().strip()) / 20)

    return 0


# 解析sku列表
def parse_sku_list(response):
    meta = response.meta
    sp_id = meta.get('spId')
    sp_name = meta.get('spName')
    jpy = PyQuery(response.text)
    sku_divs = jpy('div.el-brand-goods')
    sku_list = list()
    for sku_div in sku_divs.items():
        sku = Sku()
        # sp_name = sku_div('a span.goods_tag').text().strip() or sp_name
        url = sku_div('h3.new_good_name a').attr('href').strip()
        sku['skuId'] = match_sku_id(url)
        sku['skuName'] = sku_div('img').attr('title').strip()
        sku['supplierId'] = sp_id
        sku['supplierName'] = sp_name
        spans = sku_div('p.PreferPrice span')
        if len(spans) == 3:
            sku['salePrice'] = parse_number(spans.eq(0).text().replace('起', ''))
            sku['originPrice'] = parse_number(spans.eq(1).text().replace('起', ''))
            sku['soldCount'] = parse_number(spans.eq(2).text().replace('销量:', '').strip())
        sku_list.append(sku)

    return sku_list


def parse_query_info(response):
    jpy = PyQuery(response.text)
    total_pages = int(jpy('div.pageSkip span').eq(0).text().strip().replace('共', '').replace('页', ''))

    return total_pages


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    result = ItemData()

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    sale_price = parse_number(jpy('span#agreementPrice').text().strip())
    origin_price = parse_number(jpy('a#price').text())
    # 价格容错
    if origin_price <= 0:
        origin_price = sale_price
    nav = jpy('div.detail-position')
    sp_id = jpy('input#fkSupplierId').attr('value')
    sp_name = jpy('div.infor-head span').text().strip()
    sp_sku_id = jpy('input#skuId').attr('value')
    sp_sku_link = jpy('a#price').attr('href')
    sku_img = jpy('img#mediumImg').attr('src')
    brand = jpy('div.detail-middle-message:contains("品牌：")')
    brand_model = jpy('div.detail-middle-message:contains("型号：")')
    cat3_id = jpy('input#fkGodCategoryId').attr('value')
    gov_catalog_id = jpy('div.detail-middle-message:contains("政府采购品目编码：")')
    gov_catalog_name = jpy('div.detail-middle-message:contains("政府采购品目名称：")')

    # -------------------------------------------------
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['skuName'] = jpy('div.detail-middle-name').text().strip()
    result['skuImg'] = sku_img.strip()
    result['catalog1Id'] = ''
    result['catalog1Name'] = ''
    result['catalog2Id'] = ''
    result['catalog2Name'] = ''
    result['catalog3Id'] = cat3_id
    result['catalog3Name'] = match_cat3name_from_nav(nav.text())
    result['govCatId'] = gov_catalog_id.text().replace('政府采购品目编码：', '').strip()
    result['govCatName'] = gov_catalog_name.text().replace('政府采购品目名称：', '').strip()
    result['salePrice'] = sale_price
    result['originPrice'] = origin_price
    brand_name = brand.text().replace('品牌：', '').strip()
    if brand_name:
        result['brandId'] = md5(brand_name)
        result['brandName'] = brand_name
    result['supplierName'] = sp_name
    if sp_sku_id:
        result['supplierSkuId'] = sp_sku_id
        plat_code = None
        if sp_id == 'D4B5D871-A8D2-4D81-ADA2-758004322BE3' or '得力' in sp_name:
            plat_code = 'deli'
        result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
    result['supplierSkuLink'] = sp_sku_link
    result['brandModel'] = brand_model.text().replace('型号：', '').strip()
    # -------------------------------------------------

    return result


# 解析group关系
def parse_group(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    gr_trs = jpy('table.detail-middle-body tr')
    group = ItemGroup()
    if gr_trs and gr_trs.size() > 1:
        ids = list()
        group['spuId'] = short_uuid()
        group['skuId'] = meta.get('skuId')
        group['batchNo'] = meta.get('batchNo')
        group['skuIdList'] = ids
        for idx, tr in enumerate(gr_trs.items()):
            if idx > 0:
                sku_id = match_sku_id(tr('td:eq(1) a').attr('href'))
                ids.append(sku_id)

    return group


# 解析sku列表
def parse_order_item(response):
    jpy = PyQuery(response.text)
    meta = response.meta
    sku_id = meta.get('skuId')
    sp_id = jpy('input#fkSupplierId').attr('value')
    sp_name = jpy('div.infor-head span').text().strip()

    orders = list()
    need_next_page = True
    rs_list = jpy('div#product-detail-6 table:eq(0) tr')
    if len(rs_list) > 1:
        prev_order = None
        same_order_no = 1
        for idx, row in enumerate(rs_list.items()):
            if idx > 0:
                tds = row('td')
                amount = int(tds.eq(1).text().strip())
                unit_price = parse_number(tds.eq(2).text().strip())
                order_time_str = tds.eq(3).text().strip()
                order_time = parse_time(order_time_str, fmt='%Y-%m-%d %H:%M')
                # 采集截止
                if order_filter.to_save(order_time):
                    order = OrderItem()
                    order['skuId'] = sku_id
                    order['count'] = amount
                    order['amount'] = unit_price * amount
                    order['orderDept'] = tds.eq(0).text().strip()
                    order['supplierId'] = sp_id
                    order['supplierName'] = sp_name
                    order['orderTime'] = order_time
                    order['batchNo'] = time_to_batch_no(order_time)
                    order['genTime'] = datetime.utcnow()
                    if prev_order and prev_order.equals(order):
                        same_order_no = same_order_no + 1
                    else:
                        same_order_no = 1
                    addition = {
                        'sameOrderNo': same_order_no,
                        'orderTimeStr': order_time_str,
                    }
                    sha1_id = build_sha1_order_id(order, addition)
                    order['id'] = sha1_id
                    order['orderId'] = sha1_id
                    orders.append(order)
                    prev_order = order
                else:
                    need_next_page = False

    next_page = jpy('input[value="下一页"]:eq(0)')
    if not need_next_page or (next_page and next_page.attr('disabled')):
        return (orders, -1)
    else:
        page_num = match_order_page_num(next_page.attr('onclick'))
        return (orders, page_num)
